package com.ljf.servlet.model;


import com.ljf.framework.context.model.LjfResponse;
import com.ljf.framework.exception.LjfException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Response for Servlet
 */
public class LjfResponseForServlet implements LjfResponse {

	/**
	 * 底层Request对象
	 */
	protected HttpServletResponse response;

	/**
	 * 实例化
	 * @param response response对象
	 */
	public LjfResponseForServlet(HttpServletResponse response) {
		this.response = response;
	}

	/**
	 * 获取底层源对象
	 */
	@Override
	public Object getSource() {
		return response;
	}

	/**
	 * 设置响应状态码
	 */
	@Override
	public LjfResponse setStatus(int sc) {
		response.setStatus(sc);
		return this;
	}

	/**
	 * 在响应头里写入一个值
	 */
	@Override
	public LjfResponse setHeader(String name, String value) {
		response.setHeader(name, value);
		return this;
	}

	/**
	 * 在响应头里添加一个值
	 * @param name 名字
	 * @param value 值
	 * @return 对象自身
	 */
	public LjfResponse addHeader(String name, String value) {
		response.addHeader(name, value);
		return this;
	}

	/**
	 * 重定向
	 */
	@Override
	public Object redirect(String url) {
		try {
			response.sendRedirect(url);
		} catch (Exception e) {
			throw new LjfException(e.getMessage());
		}
		return null;
	}

	@Override
	public PrintWriter getWriter() throws IOException {
		return response.getWriter();
	}
}
